package model

import (
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
)

// User 用户模型
type User struct {
	gorm.Model
	UID             string
	UserName        string
	Password        string
	Nickname        string
	Job             string
	Rank            int    `gorm:"default:3;comment:'行政级别[1总监 2经理 3职员]'"`
	Level           int    `gorm:"default:0;comment:'技术职级[0-7]'"`
	Status          string `gorm:"default:'active';comment:'[active激活 inactive未激活 suspend被封禁]'"`
	UserType        int    `gorm:"default:3;comment:'[1超级管理员 2管理员 3成员]'"`
	Email           string
	Mobile          string
	Intro           string
	Wechat          string
	Gender          int
	Avatar          string
	OrganizationUID string
	// Organization    Organization `gorm:"foreignKey:OrganizationUID;"`
	// Organizations []*Organization `gorm:"many2many:organization_users;foreignKey:UID;joinForeignKey:UID;References:UID;JoinReferences:UID"`
}

const (
	// PassWordCost 密码加密难度
	PassWordCost = 3
	// Active 激活用户
	Active string = "active"
	// Inactive 未激活用户
	Inactive string = "inactive"
	// Suspend 被封禁用户
	Suspend string = "suspend"
)

// GetUser 用UID获取用户
func GetUser(UID interface{}) (User, error) {
	var user User
	result := DB.Where("uid = ?", UID).First(&user)
	return user, result.Error
}

// SetPassword 设置密码
func (user *User) SetPassword(password string) error {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), PassWordCost)
	if err != nil {
		return err
	}
	user.Password = string(bytes)
	return nil
}

// SetPasswordString 设置密码
func (user *User) SetPasswordString(password string) string {
	bytes, _ := bcrypt.GenerateFromPassword([]byte(password), PassWordCost)
	return string(bytes)
}

// CheckPassword 校验密码
func (user *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	return err == nil
}
